package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"info-sys/cache"
	"info-sys/models"
	"info-sys/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	var user models.User
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不可为空",
		})
		return
	}
	redis_key := "user_id_" + strconv.Itoa(int(user.ID))
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次,禁止登录",
		})
		return

	}
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "无法查询用户",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次,2小时候再试",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
}

func Collect(c *gin.Context) {
	var collect models.Collection
	err := models.DB.Find(&collect).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}
	redis_key := "detail" + strconv.Itoa(int(collect.ID))
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&collect)
		jsonData, _ := json.Marshal(collect)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &collect)
	}
	c.JSON(200, gin.H{
		"code":    200,
		"msg":     "查询成功",
		"collect": collect,
	})

}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var life models.Life
	err := models.DB.Where("id = ?", id).First(&life).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}
	redis_key := "detail" + strconv.Itoa(int(life.ID))
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).First(&life)
		jsonData, _ := json.Marshal(life)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &life)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"life": life,
	})
}
